package com.outsider.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadUtil {
	public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) { 
		File file=new File(savePath);
		InputStream is=null;
		ByteArrayOutputStream bos=null;
		FileOutputStream fos=null;
		if (file.exists()==false)
			file.mkdirs();
		URL url;
		try {
			url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
			conn.setConnectTimeout(3000);
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");  
			is=conn.getInputStream();
			byte[] buffer=new byte[1024];
			int len=0;
			bos=new ByteArrayOutputStream();
			while ((len=(is.read(buffer)))!=-1){
				bos.write(buffer, 0, len);
			}
			file = new File(savePath+File.separator+fileName);
			fos=new FileOutputStream(file);
			fos.write(bos.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
		try{
			if (bos!=null) bos.close();
			if (is!=null) is.close();
			if (fos!=null) fos.close();
		}
		catch(IOException e){
			e.printStackTrace();
		}
		
	}
}
}
